local Msg = require("core.Msg")
local MailManager = require("mail.MailManager")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local Broadcast = require("broadcast.Broadcast")
local RoleDBLogic = require("role.RoleDBLogic")
local Lang = require("common.Lang")
local FilterUtil = require("common.FilterUtil")
local Util = require("common.Util")
local Log = require("common.Log")
local ObjHuman = require("core.ObjHuman")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local MailExcel = require("excel.mail")
local ItemDefine = require("bag.ItemDefine")
local EquipLogic = require("equip.EquipLogic")
local FuwenLogic = require("fuwen.FuwenLogic")
local LogDefine = require("common.LogDefine")
local FuwenGrid = require("fuwen.FuwenGrid")

function makeMail(net, data)
    net.uuid = data._id
    net.identity = data.identity and data.identity or ""
    net.type = data.type
    net.senderName = data.senderName or Lang.MAIL_SYSTEM_NAME
    net.sendTime = data.time
    net.read = data.read or 0
    net.get = data.get or 0
    net.head = data.head or 0
    net.flag = data.flag or 0
    net.fbTime = tonumber(data.fbTime) or 0
    net.fbContent = data.fbContent or ""
    net.fbHead = data.fbHead or 0
    net.fbLv = data.fbLv or 0
    net.expireTime = data.expireTime or 7 * 86400
end

MAX_PACKET_CNT = 30
MAX_PERSON_MAIL_CNT = 20
function query(human, type)
    if type == MailManager.GONGGAO then
        queryGongGao(human)
        return
    end
    local mails = MailManager.getMails(human.db._id, nil)
	local len = 0
--	local gongGaoDot = 0
	local systemDot = 0

    local msgRet = Msg.gc.GC_MAIL_QUERY        
    msgRet.isEnd = 0
    msgRet.dotFlag = 0
	for i = 1,#mails do
    	if mails[i].get == nil or mails[i].read == nil then
			systemDot = 2
    	end
    	
    	if mails[i].type == type then			
            if len >= MAX_PACKET_CNT then
                msgRet.list[0] = len
                Msg.send(msgRet, human.fd)
                len = 0
            end
            len = len + 1
            local net = msgRet.list[len]
            makeMail(net, mails[i])		
    	end
    end
    

	msgRet.isEnd = 1
    msgRet.dotFlag = systemDot
    msgRet.list[0] = len
    Msg.send(msgRet, human.fd)
end

function queryGongGao(human)
    local msgRet = Msg.gc.GC_MAIL_READ

    local config = MailExcel.gongGao[1]
    msgRet.uuid = ""
    msgRet.title = config.title 
    msgRet.content = config.content or ""
    msgRet.fbTime = 0
    msgRet.fbContent = ""
    msgRet.fbHead =  0
    msgRet.fbLv =  0
    msgRet.name =config.senderName or Lang.SYSTEM_MAIL


    msgRet.items[0] = 0
    Msg.send(msgRet, human.fd)
end

function read(human, mailUuid)
    local mail = MailManager.getMail(mailUuid)
    if not mail then
        return
    end
    if mail.receiverUuid ~= human.db._id then
        return
    end
    if not mail.read then
        mail.read = 1
        MailManager.saveMail(mail)
    end
    local msgRet = Msg.gc.GC_MAIL_READ
    msgRet.uuid = mail._id
    msgRet.title = mail.title or ""
    msgRet.content = mail.content or ""
    msgRet.fbTime = tonumber(mail.fbTime) or 0
    msgRet.fbContent = mail.fbContent or ""
    msgRet.fbHead = mail.fbHead or 0
    msgRet.fbLv = mail.fbLv or 0
    if mail.senderName ~= false and mail.senderName ~= nil then
        msgRet.name = mail.senderName
    else
        msgRet.name = Lang.SYSTEM_MAIL
    end
    local len = 0
    if mail.items then
        for _, v in ipairs(mail.items) do
            len = len + 1
            if type(v[2]) == "table" then
                -- 给装备
                if ItemDefine.isEquip(v[1]) then
                   local equipGrid = v[2]
                   Grid.makeItem(msgRet.items[len], equipGrid.id, 1, nil, equipGrid)
                end
                -- 给符文
                if ItemDefine.isFuwen(v[1]) then
                   local fuwenGrid = v[2]
                   Grid.makeItem(msgRet.items[len], fuwenGrid.id, 1, nil, fuwenGrid)
                end
            else
                local cnt = v[2]
                if type(cnt) == "string" then
                   cnt = tonumber(cnt)
                end
                Grid.makeItem(msgRet.items[len], v[1], cnt)
            end
        end
    end
    msgRet.items[0] = len
    if len <= 0 and mail.get ~= 1 then
        mail.get = 1
        MailManager.saveMail(mail)
    end
    Msg.send(msgRet, human.fd)
    
    onMailChange(human)
end

function get(human, mailUuid)
 --   if human.version == nil then 
 --      return Broadcast.sendErr(human, Lang.MERGE_MAIL_GET_VERSION_ERR)
 --   end

    local mail = MailManager.getMail(mailUuid)
    if not mail then
        return
    end

    if mail.receiverUuid ~= human.db._id then
        return
    end

    if mail.get then
        Broadcast.sendErr(human, Lang.MAIL_GET_ERR)
        return
    end

    if not mail.items then
        Broadcast.sendErr(human, Lang.MAIL_NO_ITEM)
        return
    end

    mail.get = 1
    mail.read = 1
    MailManager.saveMail(mail)

    local itemCnt = 0
    local fuWenCnt = 0

    for _, v in ipairs(mail.items) do
        if type(v[2]) == "table" then
            -- 给装备
            if ItemDefine.isEquip(v[1]) then
               itemCnt = itemCnt + 1
            end
            -- 给符文
            if ItemDefine.isFuwen(v[1]) then
               fuWenCnt = fuWenCnt + 1
            end
        end
    end

    if not EquipLogic.checkEmptyCnt(human, itemCnt) then
       return
    end

    if not FuwenGrid.checkEmptyCnt(human, fuWenCnt) then
       return
    end

    local len = 0
    local msgRetItem = Msg.gc.GC_ITEM_GET_LIST
    msgRetItem.popupType = ItemDefine.checkIsWave(LogDefine.DEFINE["mail"]) and 1 or 0
    for _, v in ipairs(mail.items) do
        len = len + 1
        if type(v[2]) == "table" then
            -- 给装备
            if ItemDefine.isEquip(v[1]) then
               EquipLogic.addByEquipGrid(human, v[2], "mail")
               Grid.makeItem(msgRetItem.list[len], v[2].id, 1, nil, v[2])
            end
            -- 给符文
            if ItemDefine.isFuwen(v[1]) then
               FuwenLogic.addByGrid(human, v[2], "mail")
               Grid.makeItem(msgRetItem.list[len], v[2].id, 1, nil, v[2])
            end
        else
           local cnt = v[2]
           if type(v[2]) == "string" then
              cnt = tonumber(cnt)
           end
           BagLogic.addItem(human, v[1], cnt, "mail")
           Grid.makeItem(msgRetItem.list[len], v[1], cnt)
        end
    end
    msgRetItem.list[0] = len
    human.getEquip = nil
    Msg.send(msgRetItem, human.fd)
    
    local msgRet = Msg.gc.GC_MAIL_GET
    msgRet.uuid = mail._id
    Msg.send(msgRet, human.fd)
    
    onMailChange(human)
end

function allGet(human)
--    if human.version == nil then 
--       return Broadcast.sendErr(human, Lang.MERGE_MAIL_GET_VERSION_ERR)
--    end

    local mails = MailManager.getMails(human.db._id, MailManager.SYSTEM)
    local items = {}
    local itemEquip = {}
    for _, mail in ipairs(mails) do
        if not mail.get and mail.items then
            for _, item in ipairs(mail.items) do
                if type(item[2]) == "table" then
                    -- 给装备 给符文
                    if ItemDefine.isEquip(item[1]) or ItemDefine.isFuwen(item[1]) then
                        itemEquip[#itemEquip + 1] = item
                    end                  
                else
                   if ItemDefine.isEquip(item[1]) or ItemDefine.isFuwen(item[1]) then
                      itemEquip[#itemEquip + 1] = item
                   else
                      items[#items + 1] = item
                   end
                end 
            end
        end
    end
    -- 装备符文
    local itemCnt = 0
    local fuWenCnt = 0
    for _, v in pairs(itemEquip) do
       if ItemDefine.isEquip(v[1]) then
          itemCnt = itemCnt + 1
       end
       -- 给符文
       if ItemDefine.isFuwen(v[1]) then
          fuWenCnt = fuWenCnt + 1
       end
    end
    if not EquipLogic.checkEmptyCnt(human, itemCnt) then
       return
    end

    if not FuwenGrid.checkEmptyCnt(human, fuWenCnt) then
       return
    end

    -- 更新邮件
    for _, mail in ipairs(mails) do
       if not mail.get and mail.items then
           mail.get = 1
           mail.read = 1
           MailManager.saveMail(mail)
       end
    end

    -- 给道具
    local tlist = BagLogic.sameItemTogether(items)
    if tlist then
        for _, item in pairs(tlist) do
            BagLogic.addItem(human, item[1], item[2], "mail")
        end
    end

    -- 装备符文
    for _, v in pairs(itemEquip) do
        if ItemDefine.isEquip(v[1]) then
            if type(v[2]) == "table" then
                EquipLogic.addByEquipGrid(human, v[2], "mail")
            else
                for i = 1,v[2] do
                    local grid = EquipLogic.makeEquip(v[1])
                    EquipLogic.addByEquipGrid(human, grid, "mail")
                end
            end
        end 
        --  给符文
        if ItemDefine.isFuwen(v[1]) then
            if type(v[2]) == "table" then
                FuwenLogic.addByGrid(human, v[2], "mail")
            else
                for i = 1,v[2] do
                    local grid = FuwenGrid.create(v[1])
                    FuwenLogic.addByGrid(human, grid, "mail")
                end
            end
        end 
    end
    human.getEquip = nil

    -- 道具
    local len = 0
    local msgRetItem = Msg.gc.GC_ITEM_GET_LIST
    msgRetItem.popupType = ItemDefine.checkIsWave(LogDefine.DEFINE["mail"]) and 1 or 0
    if tlist then
        for _, item in pairs(tlist) do
            if len >= #msgRetItem.list then
               break
            end
            len = len + 1
            Grid.makeItem(msgRetItem.list[len], item[1], item[2])
         end
    end
    

    -- 给装备
    for _, v in pairs(itemEquip) do
       if len >= #msgRetItem.list then
          break
       end

       if ItemDefine.isEquip(v[1]) then
           if type(v[2]) == "table" then
               len = len + 1
               Grid.makeItem(msgRetItem.list[len], v[1], 1, nil, v[2])
           else
               for i = 1,v[2] do
                   local grid = EquipLogic.makeEquip(v[1])
                   len = len + 1
                   Grid.makeItem(msgRetItem.list[len], v[1], 1, nil, grid)
               end
           end
       end
       -- 给符文
       if ItemDefine.isFuwen(v[1]) then
           if type(v[2]) == "table" then
               len = len + 1
               Grid.makeItem(msgRetItem.list[len], v[1], 1, nil, v[2])
           else
               for i = 1,v[2] do
                   local grid = FuwenGrid.create(v[1])
                   len = len + 1
                   Grid.makeItem(msgRetItem.list[len], v[1], 1, nil, grid)
               end
           end
       end
    end
    msgRetItem.list[0] = len
    Msg.send(msgRetItem, human.fd)

    query(human, MailManager.SYSTEM)	
	onMailChange(human)
end

function del(human, mailUuid)
    local mail = MailManager.getMail(mailUuid)
    if not mail then
        return
    end
    MailManager.del(mailUuid)
    local msgRet = Msg.gc.GC_MAIL_DEL
    msgRet.uuid = mailUuid
    Msg.send(msgRet, human.fd)
    
    onMailChange(human)
end

CHAT_CD = 20-- 发送cd时间
function sendMail(human, identity, content)
    do return end
end

function allDel(human, type)
    MailManager.delAll(human.db._id,type)
    local msgRet = Msg.gc.GC_MAIL_ALL_DEL
    msgRet.delStr = ""
    Msg.send(msgRet, human.fd)
    query(human, type)
    
    onMailChange(human)
end

function onMailChange(human)
    RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_204)
end

function isDot(human)
	local mails = MailManager.getMails(human.db._id, nil)
	if not mails then
		return false
	end
	for i = 1,#mails do
    	if mails[i].read == nil then 
        	return true
    	end
	end
	
    return false
end

local CLEAN_MAIL_LIST = {}
function cleanNilContent(human)
    local mails = MailManager.getMails(human.db._id, nil)
    local cleanCnt = 0
    for i = 1, #mails do
        local mail = mails[i]
        if mail.content == nil then
            cleanCnt = cleanCnt + 1
            CLEAN_MAIL_LIST[cleanCnt] = mail._id            
        end
    end

    for i = 1, cleanCnt do
        del(human, CLEAN_MAIL_LIST[i])
    end
end